<template>
  <li class="todo-item">
    <!-- 完成状态复选框 -->
    <input type="checkbox" :checked="todo.completed" @change="handleToggle" />
    <!-- 待办事项标题 -->
    <span :class="{ completed: todo.completed }">{{ todo.title }}</span>
    <!-- 删除按钮 -->
    <button @click="handleDelete" class="delete-button">删除</button>
  </li>
</template>

<script setup>
import { defineProps, defineEmits, watch } from 'vue';

// 定义props
const props = defineProps({
  todo: {
    type: Object,
    required: true,
  },
});

// 定义emit事件
const emit = defineEmits(['toggle', 'delete', 'update']);

// 监听todo对象的变化
watch(
  () => props.todo,
  (newTodo) => {
    // 当todo对象发生变化时，通知父组件
    emit('update', newTodo);
  },
  { deep: true },
);

// 监听completed状态的变化
watch(
  () => props.todo.completed,
  (newCompleted) => {
    console.log(`待办事项 ${props.todo.title} 的完成状态变更为: ${newCompleted}`);
  },
);

// 处理切换完成状态
const handleToggle = () => {
  emit('toggle', props.todo.id);
};

// 处理删除
const handleDelete = () => {
  emit('delete', props.todo.id);
};
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.completed {
  text-decoration: line-through;
  color: #999;
}

.delete-button {
  margin-left: auto;
  padding: 4px 8px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
